<template>
  <div id="canvas" v-loading="loading" :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts';
require('echarts/theme/macarons'); // echarts theme
export default {
  name: 'BarChart',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    defaultData: {
      type: Object,
      default: () => {}
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '342px'
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      chart: null
    };
  },
  watch: {
    defaultData: {
      deep: true,
      handler() {
        this.initChart();
      }
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el);
      if (this.defaultData.xAxis.data.length) {
        this.chart.setOption(this.defaultData);
      } else {
        // 展示暂无数据
        this.$el.innerHTML = '-暂无数据-';
        this.$el.style.cssText = `text-align:center; color: #999; border: none;line-height: ${this.height}; width: ${this.width}; height: ${this.height}`;
        this.$el.removeAttribute('_echarts_instance_');
      }
    },
    resizeChart() {
      this.chart ? this.chart.resize() : '';
    }
  }
};
</script>
